import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { message, Table, Image, Switch, Button, Modal, Tooltip, Upload, Space } from 'antd'
import { FolderAddOutlined, ExportOutlined, ImportOutlined } from '@ant-design/icons'
import { fetchItems, removeItem, updateItem, addMulItems } from '../../api/itemLists'
import SearchBar from '../../components/SearchBar'
import { exportExcelTpl, writeExcel } from '@u/xlsx'
export default function ItemLists() {
  const navigate = useNavigate() //跳转路由
  //初始化获取商品列表的数据
  const [itemList, setItemLists] = useState([])
  useEffect(() => {
    fetchItems().then(res => {

      if (res.data.code === 200) {
        console.log(res);
        setItemLists(res.data.data.lists)
        setTotal(res.data.data.total)
      }
    })
  }, [])

  //初始化获取商品列表的数据
  // 搜索关键字和日期
  const searchParams = {
    keyWord: '',
    start: '',
    end: ''
  }
  const handleSearch = (params) => {
    searchParams.keyWord = params.keyWord;
    searchParams.start = params.range[0];
    searchParams.end = params.range[1];
    fetchItems({ ...searchParams }).then(res => {

      if (res.data.code === 200) {

        message.success('搜索成功', 2, () => {
          navigate(0)
        })
      }
    })

  }
  // 搜索关键字和日期
  //表格的初始数据
  const columns = [
    {
      title: '商品名',
      dataIndex: 'itemName',
      key: 'itemName',
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '商品描述',
      dataIndex: 'desc',
      key: 'desc',
      render: (value, row) => {
        return (
          <>
            <Tooltip placement="bottom" title={value}>
              <span>
                {value.substr(0, 15) + '...'}
              </span>
            </Tooltip>
          </>
        )
      }
    },
    {
      title: '销量',
      dataIndex: 'sale',
      key: 'sale',
    },
    {
      title: '上下架',
      dataIndex: 'onsale',
      key: 'onsale',
      render: (value, row, index) => {
        const onChange = (checked) => { //点击开关修改上下架状态
          updateItem({ //修改商品的请求
            id: row.id,
            onsale: row.onsale
          }).then(res => {
            if (res.data.code === 200) {
              message.success(res.data.msg, 2, () => {
                navigate(0)
              })
            }
          })
        };
        return (
          <>
            <Switch defaultChecked={value} onChange={onChange} />
          </>
        )
      },
    },
    {
      title: '上架时间',
      dataIndex: 'createAt',
      key: 'createAt',
    },
    {
      title: '封面',
      dataIndex: 'thumb',
      key: 'thumb',
      render: (value, row, index) => {
        return (
          <>
            <Image
              width={80}
              src={value}
            />
          </>
        )

      }
    },
    {
      title: '操作',
      render: (value, row, index) => {

        return (

          <>
           <Space size={5}>
           <Button 
            size="small"
            type="primary" 
            danger 
            onClick={
              () => {

                Modal.confirm({
                  title: '删除商品',
                  content: '该操作会彻底删除商品,确定继续吗?',
                  onOk: () => {
                    removeItem({ id: row.id }).then(res => {
                      if (res.data.code === 200) {
                        message.success('删除成功', 2, () => {
                          navigate(0)
                        })
                      }
                    })
                  }
                })
              }
            }>删除</Button>

            <Button 
            size="small"
            onClick={
              () => {
                navigate('/itemUpdate', {
                  state:{
                    id:row.id
                  }
                })
              }
            }>编辑</Button>
           </Space>
            
          </>
        )
      }

    }
  ];
  //表格的初始数据
  //表格的分页数据
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  //表格的分页数据
  //导出模板的点击事件
  const exportFile = () => {
    // 导出excel模板
    exportExcelTpl([
      {
        商品名: '商品n',
        商品价格: 10,
        商品描述: '这是商品描述',
        '上下架(1上架0下架)': 1,
        图片: ''
      }
    ], 'xxx表')
  }
  //导出模板的点击事件
  // 导入商品excel模板
  const uploadXlsx = async (file) => {
    writeExcel(file, el => {
      return {
        itemName: el.商品名,
        price: el.商品价格,
        desc: el.商品描述,
        onsale: el['上下架(1上架0下架)'],
        thumb: el.图片
      }
    }).then(data => {
      // 调用批量添加商品
      addMulItems({
        items: data
      }).then(res => {
        if (res.data.code === 200) {
          message.success(res.data.msg, 2, () => {
            navigate(0)
          })
        }
      })
    })

  }
  // 导入商品excel模板
  return (
    <div>
      <SearchBar handleSearch={handleSearch} />
      <Button  type="primary" onClick={() => {
        navigate("/itemAdd")
      }}
        icon={<FolderAddOutlined />}  >
        新增商品
      </Button>
      <Button
        style={{ margin: "0 10px" }}
        type="primary"
        onClick={exportFile}
        icon={<ExportOutlined />}>
        导出模板
      </Button>

      <Upload
        accept=".xlsx, .xls"
        action=''
        beforeUpload={(file) => {
          // 导入excel
          uploadXlsx(file)
          return false
        }}
      >
        <Button type="primary"
          icon={<ImportOutlined />}>
          批量导入
        </Button>
      </Upload>

      <Table
        rowKey={'id'}
        
        scroll={{ y: 420 }}
        pagination={{
          defaultCurrent: page,
          defaultPageSize: pageSize,
          total,
          showQuickJumper: true,
          position: ['bottomCenter'],//设置分页器的位置
          onChange: (_page, _pageSize) => {
            setPage(_page)
            setPageSize(_pageSize)
            fetchItems({
              page,
              pageSize
            }).then(res => {
              if (res.data.code === 200) {
                message.success('分页跳转成功', 2, () => {
                  navigate(0)
                })
              }
            })
          }
        }}
        dataSource={itemList}
        columns={columns} />;
    </div>
  )
}
